package com.bjy.qa.service.tools.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjy.qa.dao.tools.UploadDao;
import com.bjy.qa.entity.MyPage;
import com.bjy.qa.entity.ResponsePagingData;
import com.bjy.qa.entity.tools.Upload;
import com.bjy.qa.service.tools.IUploadService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UploadService implements IUploadService {
    @Resource
    UploadDao uploadDao;

    @Override
    public ResponsePagingData list(MyPage<Upload> myPage) throws Exception {
        Page<Upload> page = new Page(myPage.getPageNum(), myPage.getPageSize()); // 构造待查询 page 对象
        page.setOrders(myPage.getOrders()); // 设置排序字段

        // 构造待查询 QueryWrapper
        Upload upload = myPage.getQuery();
        QueryWrapper<Upload> queryWrapper = new QueryWrapper<>();
        if (upload != null) {
            if (StringUtils.isNotBlank(upload.getFileName())) {
                queryWrapper.like("file_name", upload.getFileName());
            }
        }
        queryWrapper.orderByDesc("created_at"); // 设置排序方式（根据创建时间倒序

        page = uploadDao.selectPage(page, queryWrapper); // 按分页查询

        myPage.setTotalRecords(page.getTotal()); // 设置返回总记录数

        return new ResponsePagingData(myPage, page.getRecords());
    }

    @Override
    public Upload select(Long id) {
        return uploadDao.selectById(id);
    }

    @Override
    public int add(Upload upload) {
        return uploadDao.insert(upload);
    }

    @Override
    public int update(Upload upload) {
        // 更新数据需要清除 UpdatedTime 和 CreatedTime，否则不会自动更新修改时间
        upload.setUpdatedAt(null);
        upload.setCreatedAt(null);

        return uploadDao.updateById(upload);
    }

    @Override
    public int delete(Long id) {
        return uploadDao.deleteById(id);
    }

}
